import { FastifyInstance } from "fastify";
import multer from "fastify-multer";
import fs from "fs";
import { createToken } from "@helpers";
import { config } from "@config";

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, `${process.cwd()}/files/avatars`);
    },
    filename: async function (req, file, cb) {
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        const [_, type] = file.originalname.split(".");
        cb(null, req.student.id + "-" + createToken(12) + "." + type);
    },
});
const allowedTypes = ["png", "jpg", "webp"];

const upload = multer({
    storage,
    fileFilter: function (req, file, cb) {
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        const [_, type] = file.originalname.split(".");
        if (!allowedTypes.includes(type))
            cb(new Error(`Тип файла ${type} не поддерживается.`));
        if (file.size > 10_240)
            cb(new Error("Файл должен весить меньше чем 10mb."));
        cb(null, true);
    },
});

export const student = async (fastify: FastifyInstance) => {
    fastify.post(
        "/student/uploadAvatar",
        {
            preHandler: [fastify.auth("student"), upload.single("avatar")],
            schema: {
                tags: ["student"],
            },
        },
        async (req, res) => {
            if (req.student.photo)
                fs.unlinkSync(
                    `${process.cwd()}/files/avatars/${req.student.photo}`
                );
            req.student.update({
                photo: req.file.filename,
            });
            return res.send({
                photo: req.file.filename
                    ? "https://" +
                      config.host +
                      "/files/avatars/" +
                      req.file.filename
                    : null,
            });
        }
    );
};
